package com.hitqz.robot.netty.encoder;

import com.hitqz.robot.api.dispatch.model.MessageDto;
import com.hitqz.robot.netty.NettyClient;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

/**
 * @author xupkun
 * @date 2023/8/4
 */
@Slf4j
public class Robot2ServerEncoder extends MessageToByteEncoder<MessageDto> {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, MessageDto messageRobotDto, ByteBuf byteBuf) throws Exception {
        byteBuf.writeShort(0xEB90);
        byteBuf.writeBytes(new byte[] {
            0x00 , 0x01
        });
        byte[] clientId = new byte[32];
        byte[] clientIdData = NettyClient.clientId.getBytes(StandardCharsets.UTF_8);
        System.arraycopy(clientIdData,0, clientId, 0, clientIdData.length);
        byteBuf.writeBytes(clientId);
        byteBuf.writeInt(messageRobotDto.getSn());
        byteBuf.writeShort(messageRobotDto.getCmd());
        byteBuf.writeInt(messageRobotDto.getData().length);
        byteBuf.writeBytes(messageRobotDto.getData());
        if(log.isDebugEnabled()) {
            log.debug("send 2 server {}", new String(messageRobotDto.getData(), StandardCharsets.UTF_8));
        }
    }

}
